/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.phoenix.repository.query.jql;

import javax.jcr.query.InvalidQueryException;

import net.phoenix.repository.query.jql.antlr.JQLTokenTypes;

/**
 * Jigsaw server
 * 
 * @author <a href="shamphone@gmail.com">Li XiongFeng</a>
 * @date 2012-4-21
 * @version 1.0.0
 */
public class QueryAST extends JQLBaseAST {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2481790789699202664L;

	public FromClauseAST getFromClauseAST() {
		JQLBaseAST selectFrom = this.getChild(JQLTokenTypes.SELECT_FROM);
		if (selectFrom != null)
			return (FromClauseAST) selectFrom.getChild(JQLTokenTypes.FROM);
		return null;
	}

	public SelectClauseAST getSelectClauseAST() {
		JQLBaseAST selectFrom = this.getChild(JQLTokenTypes.SELECT_FROM);
		if (selectFrom != null)
			return (SelectClauseAST) selectFrom.getChild(JQLTokenTypes.SELECT);
		return null;
	}

	public WhereAST getWhereAST() {
		return (WhereAST) this.getChild(JQLTokenTypes.WHERE);

	}

	public OrderByAST getOrderByAST() {
		return (OrderByAST) this.getChild(JQLTokenTypes.ORDER);
	}

	/**
	 * Convert to JQL
	 * 
	 * @return
	 */
	public void generateSQL(JQL2SQL collector) throws InvalidQueryException {
		StringBuffer buffer = new StringBuffer();
		this.getSelectClauseAST().generateSQL(collector);
		buffer.append(collector.pop());		
		this.getFromClauseAST().generateSQL(collector);
		buffer.append(collector.pop());
		WhereAST where = this.getWhereAST();
		if (where != null) {
			this.getWhereAST().generateSQL(collector);
			buffer.append(collector.pop());
		}
		OrderByAST order = this.getOrderByAST();
		if (order != null) {
			order.generateSQL(collector);
			buffer.append(" ");
			buffer.append(collector.pop());
		}
		//buffer.insert(0, " FROM node JOIN p_js_primarytype ON (p_jcr_primarytype.node_id=node.pkid AND p_jcr_primarytype.value='"+this.getFromClauseAST().getSource().toString()+"')" );
		//buffer.insert(0, " FROM node " + collector.pop());		
		//buffer.insert(0, collector.pop());
		collector.push(buffer.toString());
	}

}
